<template lang="pug">
  .upload-body
    .upload
      .upload-container
        .upload-header
          el-button(icon="el-icon-arrow-left" size="mini" @click="$router.back()") 返回
          .upload-header-title {{!$route.params.id ? '上传材料' : '编辑材料'}}
        .upload-content
          .upload-form-bd
            .upload-form-bd-header
              .form-bd-title 基本信息
            el-form(
              :model="form"
              :rules="rules"
            )
              el-form-item(prop="brandId")
                el-select(size="mini" placeholder="请选择材料品牌" v-model="form.brandId")
                  el-option(
                    v-for="item in brands"
                    :key="item.brandId"
                    :label="item.name"
                    :value="item.brandId"
                  )
            .form-item
              .form-item-label.form-item-label_import 材料名称
              .form-item-bd
                el-input(size="mini" placeholder="请输入材料名称" v-model="form.name")
            .form-item
              .form-item-label.form-item-label_import 材料品牌
              .form-item-bd
                el-select(size="mini" placeholder="请选择材料品牌" v-model="form.brandId")
                  el-option(
                    v-for="item in brands"
                    :key="item.brandId"
                    :label="item.name"
                    :value="item.brandId"
                  )
            .form-item
              .form-item-label.form-item-label_import 生产场地
              .form-item-bd
                el-select(size="mini" placeholder="选择" v-model="form.country" @change="selectProvince")
                  el-option(
                    v-for="item in province"
                    :key="item.keyColumn"
                    :label="item.valueColumn"
                    :value="item.keyColumn"
                  )
            .form-item
              .form-item-label.form-item-label_import 材料型号
              .form-item-bd
                el-input(size="mini" placeholder="请输入材料型号" v-model="form.materialModel")
            .form-item
              .form-item-label.form-item-label_import 材料属性
              .form-item-bd
                el-radio-group(v-model="form.attribute")
                  el-radio(:label="1") 硬装
                  el-radio(:label="2") 软装
            .form-item.form-item-top
              .form-item-label.form-item-label_import 材料所属业态
              .form-item-bd.form-item-width
                el-checkbox-group(v-model="form.styles" v-if="styleList.length")
                  el-checkbox(v-for="item in styleList" :key="item.styleId" :label="item.styleId") {{item.styleName}}
            .form-item
              .form-item-label.form-item-label_import 材料分类
              .form-item-bd
                el-select(size="mini" placeholder="请选择" v-model="category.stair_id" @change="changeCategory($event, 'stair', 'second')")
                  el-option(
                    v-for="item in category.stair"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  )
                el-select(size="mini" v-if="category.second.length" placeholder="请选择" v-model="category.second_id" @change="changeCategory($event, 'second', 'three')")
                  el-option(
                    v-for="item in category.second"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  )
                el-select(size="mini" v-if="category.three.length" placeholder="请选择" v-model="category.three_id" @change="changeCategory($event, 'three', 'four')")
                  el-option(
                    v-for="item in category.three"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  )
                el-select(size="mini" v-if="category.four.length" placeholder="请选择" v-model="category.four_id" @change="changeCategory($event, 'four', 'five')")
                  el-option(
                    v-for="item in category.four"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  )
            .form-item
              .form-item-label.form-item-label_import 供货周期
              .form-item-bd
                el-input(size="mini" placeholder="请输入供货周期" v-model="form.supplyCycle")
              .form-item-info 天
            .form-item
              .form-item-label.form-item-label_import 预计送样时间
              .form-item-bd
                el-input(size="mini" placeholder="请输入预计送样时间" v-model="form.serviceTime")
              .form-item-info 天
          .upload-form-bd
            .upload-form-bd-header
              .form-bd-title 规格设置
              el-popover(
                placement="bottom"
                popper-class="model-popover"
                width="200"
                trigger="click"
                :visible-arrow="false"
              )
                .model-body
                  .model-list
                    .model-item(v-for="item, index in specModal" :key="index" @click.stop="changeModel(item, 'spec')")
                      .model-item-title {{item.templateName}}
                      .model-item-handle
                        .iconfont.icon-edit(@click.stop="editModelList(item, 'editSpecModel')")
                        .iconfont.icon-trash(@click.stop="delModelList(item)")
                .form-bd-select(slot="reference" v-show="specModal.length")
                  .form-bd-select-value(:class="{ 'form-bd-select-value-placeholder' : !currentSpecModel.templateName }") {{currentSpecModel.templateName ? currentSpecModel.templateName : '更换模板'}}
                  .form-bd-select-icon.el-icon-arrow-down
              .form-bd-header-handle
                .form-bd-header-btn(v-if="currentSpecModel.id" @click="saveSpecModal") 保存模板
                .form-bd-header-btn(@click="addSpecModal('editSpecModel')") 存为新模板
            .form-item.form-item-start
              .form-item-label.form-item-label_import 材料规格
              .form-item-spec
                draggable(:list="form.spec.items", v-bind="dragOptions" @end="draggableEnd")
                  transition-group(type="transition" name="flip-list" tag="div")
                    .spec-table(v-for="(item, index) in form.spec.items", :key="`spec_${index}`" v-if="form.spec.items.length")
                      .spec-table-header
                        .spec-hd-value
                          .spec-hd-value-label 规格名称
                          .spec-hd-value-bd
                            el-input(size="mini" placeholder="请输入规格" v-model="item.name" @change="changeSpecName(item, index)")
                        .spec-hd-handle(@click="delSpec(item, index)")
                          .icon-trash
                          .spec-hd-handle-btn 删除
                      .spec-table-body
                        .spec-table-body-label 规格值
                        .spec-table-body-value(v-for="(row, rowIndex) in item.values" :key="rowIndex" v-if="item.name")
                          .spec-table-body-input
                            .iconfont.el-icon-error(@click="delSpecValue(row, rowIndex, item.values)")
                            el-input(v-model="row.name" size="mini" @change="changeSpecValue(item, row, index, rowIndex)")
                          .spec-table-body-uploadbtn(v-if="item.showUploadBtn")
                            .spec-table-body-img(v-if="row.image", @click="seeImage(row.image)" :style="row.image | filterUrl")
                              .iconfont.el-icon-error(@click="deleteImage(row, rowIndex)")
                            .spec-table-body-upload(v-else) 上传图片
                              input.el-input(type="file" accept="image/png, image/jpeg, image/jpg" @change="changeFile($event, index, rowIndex)")
                        .spec-table-body-ft(@click="addSpec(item)" v-if="item.name") 添加规格值
                .spec-table-handle
                  el-button(size="mini" icon="el-icon-plus" plain @click="settingSpec") 添加规格
                  .spec-table-handle-info 最多3个
            .form-item.form-item-start.spec-sku(v-if="form.spec.prices.body.length")
              .form-item-label.form-item-label_import 规格明细
              .spec-sku-table
                .spec-sku-info SKU表将根据规格的变化动态生成，请填写价格、库存等信息
                .spec-sku-table-body
                  navbar(:navbar="form.spec.prices.header")
                  .table-list
                    .table-tr(v-for="row, rowIndex in form.spec.prices.body" :key="`input_${rowIndex}`" v-if="rowIndex === 0")
                      .table-td(
                        v-for="item, index in row"
                        :key="index"
                      )
                        .table-td-body.table-td-input(v-if="index > (row.length - 6)")
                          el-input(size="mini" placeholder="0.00" v-if="index === (row.length - 5)" @change="changePrice(5, 'min_selling_price')" v-model="skuForm.min_selling_price")
                          el-input(size="mini" placeholder="0.00" v-if="index === (row.length - 4)" @change="changePrice(4, 'max_selling_price')" v-model="skuForm.max_selling_price")
                          el-input(size="mini" placeholder="0.00" v-if="index === (row.length - 3)" @change="changePrice(3, 'shop_price')" v-model="skuForm.shop_price")
                          el-input(size="mini" placeholder="请输入单位" v-if="index === (row.length - 2)" @change="changePrice(2, 'unit')" v-model="skuForm.unit")
                          el-input(size="mini" placeholder="0" v-if="index === (row.length - 1)" @change="changePrice(1, 'store_count')" v-model="skuForm.store_count")
                        .table-td-body(v-else)
                      .table-td.table-td-del
                    .table-tr(v-for="row, rowIndex in form.spec.prices.body" :key="rowIndex")
                      .table-td(
                        v-for="item,index in row"
                        :key="index"
                      )
                        .table-td-body.table-td-input(v-if="index > (row.length - 6)")
                          el-input(size="mini" v-model="row[index]" placeholder="请输入价格" @change="changeCostPrice(item, index, row)" v-if="index === (row.length - 5)")
                          el-input(size="mini" v-model="row[index]" placeholder="请输入价格" @change="changeCostPrice(item, index, row)" v-else-if="index === (row.length - 4)")
                          el-input(size="mini" v-model="row[index]" placeholder="请输入价格" @change="changeCostPrice(item, index, row)" v-else-if="index === (row.length - 3)")
                          el-input(size="mini" v-model="row[index]" placeholder="请输入单位" @change="changeCostPrice(item, index, row)" v-else-if="index === (row.length - 2)")
                          el-input(size="mini" placeholder="请输入库存" v-model="row[index]" @change="changeCostPrice(item, index, row)" type="number" v-else)
                        .table-td-body(v-else) {{item}}
                      .table-td.table-td-del(@click="deleteSku(row, rowIndex)") 删除
          .upload-form-bd
            .upload-form-bd-header
              .form-bd-title 属性设置
              el-popover(
                placement="bottom"
                popper-class="model-popover"
                width="200"
                trigger="click"
                :visible-arrow="false"
              )
                .model-body
                  .model-list
                    .model-item(v-for="item, index in attrModal" :key="index" @click.stop="changeModel(item, 'attr')")
                      .model-item-title {{item.templateName}}
                      .model-item-handle
                        .iconfont.icon-edit(@click.stop="editModelList(item, 'editAttrModel')")
                        .iconfont.icon-trash(@click.stop="delAttrModelList(item)")
                .form-bd-select(slot="reference" v-show="attrModal.length")
                  .form-bd-select-value {{currentAttrModel.templateName}}
                  .form-bd-select-icon.el-icon-arrow-down
              .form-bd-header-handle
                .form-bd-header-btn(v-if="currentAttrModel.id" @click="saveAttrModal") 保存模板
                .form-bd-header-btn(@click="addSpecModal('editAttrModel')") 存为新模板
            .form-item.form-item-start
              .form-item-label.form-item-label_import 材料属性
              .form-item-spec
                draggable(:list="form.attr", v-bind="dragOptions")
                  transition-group(type="transition" name="flip-list" tag="div")
                    .spec-table(v-for="(item, index) in form.attr", :key="`attr_${index}`" v-if="form.attr.length")
                      .spec-table-header
                        .spec-hd-value
                          .spec-hd-value-label 属性名称
                          .spec-hd-value-bd
                            el-input(size="mini" placeholder="请输入属性" v-model="item.name" @change="changeAttrName(item, index)")
                        .spec-hd-handle(@click="delAttr(item, index)")
                          .icon-trash
                          .spec-hd-handle-btn 删除
                      .spec-table-body
                        .spec-table-body-label 属性值
                        .spec-table-body-value(v-for="(row, rowIndex) in item.values" :key="rowIndex" v-if="item.name")
                          .spec-table-body-input
                            .iconfont.el-icon-error(@click="delAttrValue(row, rowIndex, item.values)")
                            el-input(v-model="row.name" size="mini")
                        .spec-table-body-ft(@click="addAttr(item)" v-if="item.name") 添加属性值
                .spec-table-handle
                  el-button(size="mini" icon="el-icon-plus" plain  @click="settingAttr") 添加属性
          .upload-form-bd(v-if="form.fixParams.length")
            .upload-form-bd-header
              .form-bd-title 固定属性
            .form-item.form-item-start
              .form-item-label.form-item-label_import 固定属性
              .form-item-fixed-attr
                .fixed-attr-item(v-for="item, index in form.fixParams" :key="index")
                  .fixed-attr-item-bd
                    .fixed-attr-item-header
                      .fixed-attr-item-header_label 属性名称：
                      .fixed-attr-item-header_value {{item.attributeName}}
                    .fixed-attr-item-value
                      .fixed-attr-item-value_label 属性值
                      .fixed-attr-item-value_bd
                        el-input(size="mini" v-model="item.attributeValue" placeholder="请输入属性值")
          .upload-form-bd(v-if="form.descriptions.length")
            .upload-form-bd-header
              .form-bd-title 其他说明
            .form-item.form-item-start.form-description-item(v-for="item, index in form.descriptions" :key="index")
              .form-item-label.form-item-label_import {{item.attributeName}}
              .form-item-fixed-attr
                el-input(
                  v-model="item.attributeValue"
                  type="textarea"
                  placeholder="请输入说明（必填）"
                  resize="none"
                  rows="6"
                )
          .upload-form-bd
            .upload-form-bd-header
              .form-bd-title 图片详情
            .form-item-upload
              .form-item
                .form-item-label.form-item-label_import 材料主图
                .form-item-bd.form-item-bd-info 文件大小≤5M，建议尺寸580*420px，最多可上传5张
              .form-item
                .form-item-label
                .form-item-bd
                  el-upload(
                    action="#"
                    class="upload-demo"
                    :limit="limit"
                    :multiple="true"
                    accept="image/png, image/jpeg, image/jpg"
                    ref="uploadGrid"
                    :show-file-list="false"
                    :auto-upload="false"
                    :on-change="handleGridChange"
                    :on-exceed="handleGridExceed"
                  )
                    .form-item-add.form-item-add_upload(slot="trigger")
                      i.el-icon-plus
                      .form-item-add_text 点击上传图片
                  .form-item-add.form-item-add_img(v-for="(item, index) in form.fileGridMapping", :key="index" :style="item.fileUrl | filterUrl")
                    i.el-checkbox-iconfont.el-icon-error(@click="delGoodsImg(item, index, form.fileGridMapping)")
                    .form-item-add_operation(v-if="!item.enabled" @click="changeOriginal($event, item.fileUrl)") 设为封面
                    .form-item-add_tag(v-else) 封面
            .form-item-upload
              .form-item
                .form-item-label.form-item-label_import 详情描述
                .form-item-bd.form-item-bd-info 文件大小≤3MB；建议宽度1320px；拖动图片可调整顺序。
              .form-item(ref="detailImg")
                .form-item-label
                .form-item-bd
                  el-upload(
                    action="#"
                    class="upload-demo"
                    :multiple="true"
                    accept="image/png, image/jpeg, image/jpg"
                    ref="upload"
                    :show-file-list="false"
                    :auto-upload="false"
                    :on-change="handleChange"
                  )
                    .form-item-add.form-item-add_upload(slot="trigger")
                      i.el-icon-plus
                      .form-item-add_text 点击上传图片
                  .form-item-add.form-item-add_img(
                    v-for="(site, index) in form.materialDetail"
                    :key="index"
                    :style="site.fileUrl | filterUrl"
                    draggable="true"
                    @dragstart="handleDragStart($event, site.fileUrl)"
                    @dragover.prevent="handleDragOver($event, site.fileUrl)"
                    @dragenter="handleDragEnter($event, site.fileUrl)"
                    @dragend="handleDragEnd($event, site.fileUrl)"
                  )
                    i.el-checkbox-iconfont.el-icon-error(@click="delDetailImg(index, form.materialDetail)")
            .form-item-upload
              .form-item
                .form-item-label 材料模型文件
                .form-item-bd
                  el-upload(
                    v-show="!form.materialModelFile.length"
                    action="#"
                    class="upload-file-demo"
                    :limit="1"
                    ref="uploadFile"
                    :show-file-list="false"
                    :auto-upload="false"
                    :on-change="handleFileChange"
                  )
                    el-button(size="mini" slot="trigger") 选取文件
                  .form-item-file(v-show="form.materialModelFile.length" v-for="item, index in form.materialModelFile" :key="index")
                    .form-file-icon.icon-file
                    .form-file-name {{item.fileName}}
                    .form-file-handle(@click="deleteFile") 删除
      .upload-footer
        el-button(size="small" @click="$router.back()") 取消
        el-button(size="small" @click="submit('draft')") 存为草稿
        el-button(size="small" type="primary" @click="submit('save')") 提交审核
      //- preview-detail
      model-name-dialog(
        :show="showModelDialog"
        :skuList="modelDialogType === 'editSpecModel' ? form.spec : form.attr"
        :item="currentModelItem"
        :modelDialogType="modelDialogType"
        @close="closeModelDialog"
        @confirm="confirmModelDialog"
      )
      //- .upload-hidden(ref="upload")
  </template>
  
  <script>
  import navbar from '@/components/navbar'
  import modelNameDialog from '@/components/modal/modelNameDialog'
  // import previewDetail from '@/components/modal/previewDetail'
  import { mapState, mapActions } from 'vuex'
  import draggable from 'vuedraggable'
  import { getMaterialTemplate, getMaterialCategory, getStyles, loadSupplierBrands, FileUpload, saveOrUpdate, getMaterialDetail, saveMaterialTemplate, saveFileManage, deleteTemplate, getCategoryFixAttribute } from 'api'
  /* eslint-disable */
  export default {
    name: 'upload',
    components: {
      modelNameDialog,
      navbar,
      draggable,
      // previewDetail
    },
    computed: {
      dragOptions () {
        return {
          animation: 60,
          handle: '.spec-table'
        }
      },
      limit: {
        get () {
          return 5 - this.form.fileGridMapping.length ? 5 - this.form.fileGridMapping.length : -1
        }
      },
      ...mapState({
        userInfo: state => state.user.user
      })
    },
    data () {
      return {
        showModelDialog: false,
        modelDialogType: '',
        loading: true,
        isChange: true,
        rules: {
          brandId: [
          { required: true, message: '请选择公司性质', trigger: 'change' }
          ]
        },
        form: {
          name: '',
          brandId: '',
          country: '100000',
          materialModel: '',
          attribute: 1,
          styles: [],
          category: '',
          supplyCycle: '',
          serviceTime: '',
          isOnSales: '',
          items: [],
          table: {},
          attr: [],
          fixParams: [],
          descriptions: [],
          fileGridMapping: [],
          materialDetail: [],
          // materialTextureSu: [],
          materialModelFile: [],
          type: 1,
          code: '',
          spec: {
            items: [],
            prices: {
              header: [],
              body: []
            }
          }
        },
        province: [],
        city: [],
        deliveryTypes: [],
        uploadParams: {
          index: null,
          rowIndex: null
        },
        addressList: [],
        brands: [],
        goodsModel: {
          attrValue: '',
          specValue: ''
        },
        supplier_name: '',
        skuForm: {
          min_selling_price: '',
          max_selling_price: '',
          shop_price: '',
          unit: '',
          store_count: ''
        },
        specModal: [],
        attrModal: [],
        goodsImages: [],
        category: {
          stair: [],
          stair_id: '',
          second: [],
          second_id: '',
          three: [],
          three_id: '',
          four: [],
          four_id: '',
        },
        modelList: [], // 模型列表数据
        currentSpecModel: {}, // 当前模板
        currentAttrModel: {},
        currentModelItem: {},
        spaceList: [],
        styleList: [],
        move: {
          dragging: null
        },
        vaild: false
      }
    },
    methods: {
      ...mapActions([
        'changePreviewModal',
        'getDropdown'
      ]),
      async handleChange (file, fileList) {
        try {
          let fileObj = await this.fileUpload(file.raw)
          this.form.materialDetail.push({ ...fileObj })
        } catch (err) {
          this.$message.error(err.ResultSet.errors)
        }
      },
      async getCategoryFixAttribute (id) {
        try {
          const { ResultSet } = await this.$axios.post(getCategoryFixAttribute, { content: { categoryId: parseInt(id) } })
          if (ResultSet.userData.descriptions.length) {
            ResultSet.userData.descriptions.forEach(item => {
              item.attributeValue = ''
            })
            this.form.descriptions = ResultSet.userData.descriptions
          } else {
            this.form.descriptions = []
          }
          if (ResultSet.userData.fixSpecs.length) {
            ResultSet.userData.fixSpecs.forEach(item => {
              item.attributeValue = ''
            })
            this.form.fixParams = ResultSet.userData.fixSpecs
          } else {
            this.form.fixParams = []
          }
        } catch (err) {
           this.$message.error(err.ResultSet.errors)
        }
      },
      async handleGridChange (file, fileList) {
        try {
          let fileObj = await this.fileUpload(file.raw)
          this.form.fileGridMapping.push({ ...fileObj, enabled: false })
          this.form.fileGridMapping[0].enabled = true
          this.$refs.uploadGrid.clearFiles()
        } catch (err) {
          this.$message.error(err.ResultSet.errors)
        }
      },
      handleGridExceed () {
        this.$message.error('材料主图最多只能上传5张！')
      },
      async fileUpload (raw) {
        return new Promise(async (resolve, reject) => {
          try {
            let formData = new FormData()
            formData.append('Filedata', raw)
            formData.append("applicationId",4)
            const { ResultSet } = await this.$axios.post(FileUpload, { formData: formData, isUpload: true }, { headers:{ "Content-Type": "multipart/form-data" } })
            resolve({ ...ResultSet.Result[0] })
          } catch (err) {
            console.log(err)
            reject(err)
          }
        })
      },
      changeOriginal (ev, item) {
        this.form.fileGridMapping.forEach(row => {
          row.enabled = false
          if (row.fileUrl === item) row.enabled = true
        })
      },
      // // 删除商品图册
      delGoodsImg (item, index, arr) {
        arr.splice(index, 1)
        if (item.enabled) arr[0].enabled = true
      },
      delDetailImg (index, arr) {
        arr.splice(index, 1)
      },
      deleteFile () {
        this.form.materialModelFile = []
        this.$refs.uploadFile.clearFiles()
      },
      // 模型文件
      async handleFileChange (file, fileList) {
        try {
          let fileObj = await this.fileUpload(file.raw)
          this.form.materialModelFile.push({ ...fileObj })
        } catch (err) {
          this.$message.error(err.ResultSet.errors)
        }
      },
      // 规格处理
      // 规格调整位置更新SKU表
      draggableEnd (e) {
        this.updataTable()
      },
      // 规格名称修改
      changeSpecName (item, index) {
        if (!item.name) {
          this.form.spec.items[index].values = []
        }
        this.updataTable()
      },
      // 删除规格项
      async delSpec (item, index) {
        this.$confirm('确定删除该规格吗？', '删除规格提示', {
          customClass: 'sold-message_box',
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          confirmButtonClass: 'sold-button_sure'
        }).then(async () => {
          this.form.spec.items.splice(index, 1)
          this.setUploadBtn()
          this.updataTable()
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        })
      },
      // 删除规格属性
      delSpecValue (row, index, arr) {
        arr.splice(index, 1)
        this.updataTable()
      },
      // 规格值改变更新SKU
      changeSpecValue (item, row, index, rowIndex) {
        if (!row.name.replace(/^\s+|\s+$/g,"")) {
          this.$message.error('规格值不可以为空！')
        } else {
          row.is_selected = true
          this.updataTable()
        }
      },
      // 删除规格属性图片
      deleteImage (row, index) {
        row.image = ''
      },
      // 添加规格属性
      async addSpec (item) {
        try {
          item.values.push({
            image: '',
            is_selected: true,
            name: ''
          })
        } catch ({ msg }) {
          this.$message.error(msg)
        }
      },
      // 添加规格项
      async settingSpec () {
        try {
          if (this.form.spec.items.length >= 3) {
            this.$message.error('材料规格最多3个！')
            return
          }
          this.form.spec.items.push({
            name: '',
            showUploadBtn: false,
            values: []
          })
        } catch ({ msg }) {
          this.$message.error(msg)
        }
      },
      // 保存规格模板
      async saveSpecModal () {
        try {
          let query = JSON.parse(JSON.stringify(this.currentSpecModel))
          query.value.items.forEach(item => {
            item.values.forEach(row => {
              row.image = ''
            })
          })
          query.value = JSON.stringify(query.value)
          await this.$axios.post(saveMaterialTemplate, { content: { ...query } })
          this.$message.success('保存成功！')
        } catch (err) {
          this.$message.error(err.msg)
        }
      },
      // 新增规格模板
      async addSpecModal (type) {
        this.modelDialogType = type
        this.showModelDialog = true
      },
      
      // 属性设置
      // 保存属性模板
      async saveAttrModal () {
        try {
          let query = { ...this.currentAttrModel }
          query.value = JSON.stringify(query.value)
          await this.$axios.post(saveMaterialTemplate, { content: { ...query } })
          this.$message.success('保存成功！')
        } catch (err) {
          this.$message.error(err.msg)
        }
      },
      // 添加属性项
      async settingAttr () {
        try {
          this.form.attr.push({
            name: '',
            values: []
          })
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.goodsModel.attrValue = ''
        } catch ({ msg }) {
          this.$message.error(msg)
        }
      },
      // 修改属性名称
      changeAttrName (item, index) {
        if (!item.name) {
          this.form.attr[index].values = []
        }
      },
      // 删除属性项
      async delAttr (item, index) {
        this.$confirm('确定删除该属性吗？', '删除属性提示', {
          customClass: 'sold-message_box',
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          confirmButtonClass: 'sold-button_sure'
        }).then(async () => {
          this.form.attr.splice(index, 1)
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        })
      },
      // 添加属性值
      async addAttr (item) {
        try {
          item.values.push({
            is_selected: true,
            name: ''
          })
        } catch (err) {
          this.$message.error(err.msg)
        }
      },
      // 删除属性值
      delAttrValue (row, index, arr) {
        arr.splice(index, 1)
      },
      
      // 大图预览图片
      seeImage (file) {
        this.changePreviewModal({
          show: true,
          url: file
        })
      },
      
      // 关闭模板名称弹窗
      closeModelDialog () {
        this.showModelDialog = false
        this.currentModelItem = {}
      },
      // 确认模板名称
      confirmModelDialog () {
        this.$message.success('保存成功！')
        this.currentModelItem = {}
        this.getCateModelList()
        this.showModelDialog = false
      },
      // 替换模板
      changeModel (item, key) {
        this.$confirm('您确定要使用该模型吗？使用后会覆盖当前页面数据', '使用模型', {
          customClass: 'sold-message_box',
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          confirmButtonClass: 'sold-button_sure'
        }).then(async () => {
          if (key === 'attr') {
            this.form.attr = item.value
            this.currentAttrModel = item
          } else {
            this.form.spec = {
              items: item.value.items,
              prices: {
                header: [],
                body: []
              }
            }
            this.currentSpecModel = item
            this.setUploadBtn()
            this.updataTable()
          }
        })
      },
      // 编辑模板名称
      editModelList (item, type) {
        this.modelDialogType = type
        this.currentModelItem = item
        this.showModelDialog = true
      },
      delModelList (item) {
        this.$confirm('确定删除该模型？删除模型不影响您现在编辑的内容', '删除模型提示', {
          customClass: 'sold-message_box',
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          confirmButtonClass: 'sold-button_sure'
        }).then(async () => {
          try {
            await this.$axios.post(deleteTemplate, { content: { id: item.id } })
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            await this.getCateModelList()
          } catch (err) {
            this.$message.error(err.msg)
          }
        })
      },
      // 删除模板
      delAttrModelList (item) {
        this.$confirm('确定删除该模型？删除模型不影响您现在编辑的内容', '删除模型提示', {
          customClass: 'sold-message_box',
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          confirmButtonClass: 'sold-button_sure'
        }).then(async () => {
          try {
            await this.$axios.post(deleteTemplate, { content: { id: item.id } })
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            await this.getCateModelList()
          } catch (err) {
            this.$message.error(err.msg)
          }
        })
      },
      
      async changeFile (event, index, rowIndex) {
        let valid = false
        this.form.spec.items.map((spec, specIndex) => spec.values.map(col =>{
          if (col.image && index !== specIndex) {
            valid = true
          }
        }))
        if (valid) {
          this.$message.error('只能选择一个规格上传图片！')
          return
        }
        this.uploadParams.index = index
        this.uploadParams.rowIndex = rowIndex
        let file = event.target.files[0]
        const newFile = await this.fileUpload(file)
        this.$set(this.form.spec.items[this.uploadParams.index].values[this.uploadParams.rowIndex], 'image', `${newFile.fileUrl}`)
        this.$set(this.form.spec.items[this.uploadParams.index].values[this.uploadParams.rowIndex], 'fileId', `${newFile.fileId}`)
        this.uploadParams = { index: null, rowIndex: null }
      },
      // 详情图拖动
      handleDragStart (ev, item) {
        this.move.dragging = item
      },
      handleDragOver (e) {
        e.dataTransfer.dropEffect = 'move' // e.dataTransfer.dropEffect="move";//在dragenter中针对放置目标来设置!
      },
      handleDragEnter (e, item) {
        try {
          e.dataTransfer.effectAllowed = 'move' // 为需要移动的元素设置dragstart事件
          if (item === this.move.dragging) return
          const newItems = [...this.form.materialDetail]
          let src = null
          let dst = null
          newItems.forEach((row, index) => {
            if (row.fileUrl === this.move.dragging) src = index
            if (row.fileUrl === item) dst = index
          })
          newItems.splice(dst, 0, ...newItems.splice(src, 1))
          this.form.materialDetail = newItems
        } catch (err) {
          console.log(err)
        }
      },
      handleDragEnd (e, item) {
        this.move.dragging = null
      },
      async getArea () {
        try {
          const { data } = await this.$axios.post(getArea, { page: 1, page_size: 100  })
          this.addressList = data.ls
        } catch (err) {
          this.$message.error(err.msg)
        }
      },
      deleteSku (item, index) {
        this.form.spec.prices.body.splice(index, 1)
        if (this.form.spec.prices.body.length) {
          let len = this.form.spec.prices.header.length
          let defaultNum = 8
          let obj = {}
          this.form.spec.items.forEach((spec, specIndex) => {
            spec.values.forEach(row => {
              if (row.is_selected) obj[row.name] = specIndex
            })
          })
          // 思路： 规格中所有勾选中的规格项如果在sku表中对应位置的name不存在那么就取消勾中状态
          let newObj = {}
          this.form.spec.prices.body.forEach(bodyItem => {
            let num = 0
            for (let key in obj) {
              if (!newObj[key]) newObj[key] = 0
              if (bodyItem[obj[key]] === key) newObj[key]++
            }
          })
          for (let newKey in newObj) {
            if (!newObj[newKey]) {
              let index = this.form.spec.items[obj[newKey]].values.findIndex(val => val.name === newKey)
              if (index >= 0) this.form.spec.items[obj[newKey]].values.splice(index, 1)
            }
          }
        } else {
          this.form.spec.items.forEach((spec) => {
            spec.values = []
          })
        }
      },
      changePrice (index, key) {
        let reg = /^\d+(\.\d+)?$/
        if (index === 5 && !reg.test(this.skuForm.min_selling_price)) {
          this.$message.error('请输入正确的价格！')
          return
        }
        if (index === 4 && !reg.test(this.skuForm.max_selling_price)) {
          this.$message.error('请输入正确的价格！')
          return
        }
        if (index === 3 && !reg.test(this.skuForm.shop_price)) {
          this.$message.error('请输入正确的价格！')
          return
        }
        this.form.spec.prices.body.forEach(row => {
          this.setSkuTable(row, index, key)
        })
      },
      setSkuTable (row, num, key) {
        this.$set(row, row.length - num, this.skuForm[key] ? this.skuForm[key] : row[row.length - num])
      },
      changeGoodsCateGory () {
        this.isChange = true
      },
      async getDelivery () {
        try {
          const { data } = await this.$axios.get(getDelivery)
          this.deliveryTypes = data.deliveryList
        } catch (err) {
          this.$message.error(err.msg)
        }
      },
      async updataTable (item, headerIndex, type) {
        let spec_arr = []
        this.skuForm = {
          min_selling_price: '',
          max_selling_price: '',
          shop_price: '',
          unit: '',
          store_count: ''
        }
        // 遍历所有规格，规格属性选中后以规格项名为key规格属性为值的形式保存下来
        this.form.spec.items.forEach((items, itemsIndex) => {
          items.values.forEach(row => {
            if (row.is_selected) {
              if (!spec_arr[itemsIndex] || !spec_arr[itemsIndex].name) spec_arr[itemsIndex] = { name: items.name, values: [] }
              spec_arr[itemsIndex].values.push(row.name)
            }
          })
        })
        // 枚举选中规格
        let navbar  = []
        let arr = []
        spec_arr.forEach(spec => {
          navbar.push(spec.name)
          arr.push(spec.values)
        })
        // 如果为空清空sku
        if (!navbar.length) {
          this.form.spec.prices = { header: [], body: [] }
          return
        }
        // 为sku表头追加默认数据
        let header = ['最低市场价格', '最高市场价格', '成交价格', '单位', '库存量']
        navbar = [...navbar, ...header]
        let result = await this.reduceMultipleArr(arr)
        let body = []
        result.forEach(item => {
          let row = item.split(/&#/)
          let prices = ['', '', '', '', '']
          row = [...row, ...prices]
          body.push(row)
        })
        if (type === 'new') {
          let newBody = []
          body.forEach(bodyItem => {
            if (bodyItem[headerIndex] === item.name) {
              newBody.push(bodyItem)
            }
          })
          this.form.spec.prices = { header: navbar, body: [...this.form.spec.prices.body, ...newBody] }
        } else {
          this.form.spec.prices = { header: navbar, body: body }
        }
      },
      async changeChildCheckbox (item, row, index, rowIndex) {
        try {
          // 规格变化sku表变化
          /**
           * this.form.spec.prices.body sku表body
           * this.form.spec.prices.header sku表头
           * 当body且header 有数据规格选项改变时考虑原有数据保留情况
           * 勾选规格属性:
           *   当规格项在已有数据当中，取索引
           * **/
          if (this.form.spec.prices.body.length && this.form.spec.prices.header.length) {
            let copyBody = JSON.parse(JSON.stringify(this.form.spec.prices.body))
            let spliceArr = []
            // debugger
            // 取选中规格属性所在的规格项
            let headerIndex = this.form.spec.prices.header.findIndex(name => name === item.templateName)
            // 规格属性取消
            if (!row.is_selected) {
              // 记录当前选中规格项中所有规格属性的选中状态 没选中记录一次
              let num = 0
              item.values.forEach(valuesItem => {
                if (!valuesItem.is_selected) num++
              })
              /**
               * 如果当前规格项中所有属性都没选中，sku表中要删除规格项这一列，并且删除对应规格属性，所有价格数据重置
               * 否则只删除选中规格属性项，保留原有数据
               * **/
              if (num === item.values.length) {
                this.updataTable()
              } else {
                this.form.spec.prices.body.forEach((bodyItem, bodyIndex) => {
                  if (bodyItem[headerIndex] === row.name) spliceArr.push(bodyIndex)
                })
                for (let i = 0; i < spliceArr.length; i++) {
                  this.form.spec.prices.body.splice(spliceArr[i] - i, 1)
                }
              }
            // 规格属性选中
            } else {
              /**
               * 如果选中规格项在原有sku数据中存在，保留原有数据，并用选中规格属性与除开自己规格项中其他所有规格项中的所有规格属性组合成行的sku
               * 否则生成全新sku表
               * **/
              if (headerIndex >= 0) this.updataTable(row, headerIndex, 'new')
              else this.updataTable()
            }
          } else {
            // 生成全新sku表
            this.updataTable()
          }
        } catch (err) {
          console.log(err)
          this.$message.error(err.msg)
        }
      },
      reduceTwoArr (source1, source2) {
        let result = []
        source1.forEach(item => {
          source2.forEach(item2 => {
            result.push(`${item}&#${item2}`)
          })
        })
        return result
      },
      reduceMultipleArr (arr = []) {
        return arr.reduce((acc,currentItem)=>{
          return this.reduceTwoArr(acc,currentItem)
        })
      },
      changeCostPrice (val, index, row) {
        let reg = /^\d+(\.\d+)?$/
        if (!reg.test(val)) {
          this.$message.error('请输入正确的数字！')
          this.vaild = true
        } else {
          this.vaild = false
        }
      },
      // 获取规格模板
      async getSpecModel () {
        try {
          const { ResultSet } = await this.$axios.post(getMaterialTemplate, { content: { type: 1 } })
          if (ResultSet.userData && ResultSet.userData.templateList && ResultSet.userData.templateList.length) {
            ResultSet.userData.templateList.forEach(item => {
              if (item.value.items && item.value.items.length) {
                item.value.items.forEach(row => {
                  if (row.values.length) {
                    row.values.forEach(col => {
                      col.is_selected = true
                    })
                  }
                })
              }
            })
            if (!this.$route.params.id) {
              this.currentSpecModel = ResultSet.userData.templateList[0]
            }
            this.specModal = ResultSet.userData.templateList
          }
        } catch (err) {
          this.$message.error(err.msg)
        }
      },
      // 获取属性模板
      async getAttrModel () {
        try {
          const { ResultSet } = await this.$axios.post(getMaterialTemplate, { content: { type: 2 } })
          if (ResultSet.userData.templateList.length) {
            ResultSet.userData.templateList.forEach(item => {
              if (item.value.length) {
                item.value.forEach(row => {
                  if (row.values.length) {
                    row.values.forEach(col => {
                      col.is_selected = true
                    })
                  }
                })
              }
            })
            if (!this.$route.params.id) {
              this.currentAttrModel = ResultSet.userData.templateList[0]
              // ResultSet.userData.templateList.forEach(item => {
              //   this.currentAttrModel = 
              //   if (item.is_default) {
              //     this.currentAttrModel = item
              //   }
              // })
            }
            this.attrModal = ResultSet.userData.templateList
            // console.log(ResultSet.userData.templateList)
          }
        } catch (err) {
          this.$message.error(err.msg)
        }
      },
      async getCateModelList () {
        try {
          await this.getSpecModel()
          await this.getAttrModel()
        } catch (err) {
          console.log(err)
        }
      },
      async getSpecDetail () {
        try {
          // const { data: { goods_spec: spec } } = await this.$axios.get(getSpecDetail, { params: { model_id: this.currentSpecModel.id } })
          this.form.spec = this.currentSpecModel.value
          this.form.spec.prices = { header: [], body: [] }
          if (this.form.spec.items.length) {
            this.form.spec.items.forEach(item => {
              item.values.forEach(row => {
                row.is_selected = true
              })
            })
            this.setUploadBtn()
            this.changeChildCheckbox()
          }
        } catch (err) {
          console.log(err)
          this.$message.error(err.msg)
        }
      },
      async getAttrDetail () {
        try {
          this.form.attr = this.currentAttrModel.value
          // const { data: { goods_attr: attr } } = await this.$axios.get(getAttrDetail, { params: { model_id: this.currentAttrModel.id } })
          // this.form.attr = attr
        } catch (err) {
          console.log(err)
          this.$message.error(err.msg)
        }
      },
      // 获取规格属性
      async getDefaultModel () {
        try {
          this.loading = true
          await this.getSpecDetail()
          await this.getAttrDetail()
          this.loading = false
        } catch ({ msg }) {
          this.loading = false
          this.$message.error(msg)
        }
      },
      async init () {
        try {
          this.isInit = true
          this.loading = true
          this.isChange = false
          const { ResultSet } = await this.$axios.post(getMaterialDetail, { content: { materialId: this.$route.params.id } })
          let newForm = { ...ResultSet.userData.Material, ...ResultSet.userData, country: ResultSet.userData.Material.country + '' }
          let newSpec = {
            items: ResultSet.userData.items,
            prices: ResultSet.userData.table
          }
          newForm.spec = newSpec
          this.form = newForm
          if (this.form.categoryNode && this.form.categoryNode.length) {
            if (this.form.categoryNode.length === 4) {
              this.category.stair_id = this.form.categoryNode[this.form.categoryNode.length - 1]
              this.setCategory(this.category.stair_id, 'stair', 'second')
              this.category.second_id = this.form.categoryNode[this.form.categoryNode.length - 2]
              this.setCategory(this.category.second_id, 'second', 'three')
              this.category.three_id = this.form.categoryNode[this.form.categoryNode.length - 3]
              this.setCategory(this.category.three_id, 'three', 'four')
              this.category.three_id = this.form.categoryNode[this.form.categoryNode.length - 4]
              this.setCategory(this.category.three_id, 'four', 'four')
            } else if (this.form.categoryNode.length === 3) {
              this.category.stair_id = this.form.categoryNode[this.form.categoryNode.length - 1]
              this.setCategory(this.category.stair_id, 'stair', 'second')
              this.category.second_id = this.form.categoryNode[this.form.categoryNode.length - 2]
              this.setCategory(this.category.second_id, 'second', 'three')
              this.category.three_id = this.form.categoryNode[this.form.categoryNode.length - 3]
              this.setCategory(this.category.three_id, 'three', 'four')
            } else if (this.form.categoryNode.length === 2) {
              this.category.stair_id = this.form.categoryNode[this.form.categoryNode.length - 1]
              this.setCategory(this.category.stair_id, 'stair', 'second')
              this.category.second_id = this.form.categoryNode[this.form.categoryNode.length - 2]
              this.setCategory(this.category.second_id, 'second', 'three')
            } else if (this.form.categoryNode.length === 1) {
              this.category.stair_id = this.form.categoryNode[this.form.categoryNode.length - 1]
              this.setCategory(this.category.stair_id, 'stair', 'second')
            }
          }
          
          this.setUploadBtn()
          this.isInit = false
        } catch (err) {
          this.loading = false
          this.isInit = false
          console.log(err)
          this.$message.error(msg)
        }
      },
      setUploadBtn () {
        if (this.form.spec.items.length) {
         this.form.spec.items.forEach(item => {
            if (item.values.length) {
              item.values.forEach(row => {
                if (row.image) item.showUploadBtn = true
                else item.showUploadBtn = false
              })
            }
          })
          let status = this.form.spec.items.every((item, index) => { return !item.showUploadBtn })
          if (status) this.form.spec.items[0].showUploadBtn = true
        }
      },
      changeCategory (id, value, child) {
        if (value === 'stair') {
          this.category.second_id = ''
          this.category.second = []
          this.category.three_id = ''
          this.category.three = []
          this.category.four_id = ''
          this.category.four = []
          this.form.descriptions = []
          this.form.fixParams = []
        }
        if (value === 'second') {
          this.category.three_id = ''
          this.category.three = []
          this.category.four_id = ''
          this.category.four = []
          if (!this.isInit) {
            this.getCategoryFixAttribute(id)
          } else {
            this.form.descriptions = []
            this.form.fixParams = []
          }
        }
        if (value === 'three') {
          this.category.four_id = ''
          this.category.four = []
        }
        this.setCategory(id, value, child)
      },
      setCategory (id, value, child) {
        this.category[value].forEach(item => {
          if (item.id === id) {
            if (!item.children || !item.children.length) {
              this.form.category = item.id
            } else {
              this.form.category = ''
              this.setChildenCate(item, child)
            }
          }
        })
      },
      setChildenCate (item, child) {
        this.category[child] = item.children || []
      },
      // 获取品牌
      async getBrands () {
        try {
          const { ResultSet } = await this.$axios.post(loadSupplierBrands, { content: { reviewStatus: 2 } })
          this.brands = ResultSet.userData.brandList
          // if (data.list.length === 1) {
          //   this.form.brand_id = data.list[0].id
          // }
        } catch (err) {
          console.log(err)
          this.$message.error(err.msg)
        }
      },
      selectProvince (id) {
        this.getRegion({ id: id, type: 'city' })
      },
      // 获取行政区域
      async getRegion () {
        try {
          let arr = await this.getDropdown({key: 'region_countries'})
          this.province = arr
          // console.log(arr)
          // const { data } = await this.$axios.get(getRegion, { params: { pid: id } })
          // if (type === 'province') this.province = data
          // else this.city = data
        } catch ({ msg }) {
          this.$message.error(msg)
        }
      },
      // 获取品类
      async getCategories (key) {
        try {
          const { ResultSet } = await this.$axios.post(getMaterialCategory, { content: {} })
          this.category[key] = ResultSet.userData.roots
        } catch ({ msg }) {
          this.$message.error(msg)
        }
      },
      // 获取风格
      async getStyle () {
        try {
          const { ResultSet } = await this.$axios.post(getStyles, { content: {} })
          this.styleList = ResultSet.userData.businessStyles
        } catch ({ msg }) {
          this.$message.error(msg)
        }
      },
      // 获取空间
      async getSpace () {
        try {
          const { data } = await this.$axios.get(getSpace)
          this.spaceList = data.spaceList
        } catch ({ msg }) {
          this.$message.error(msg)
        }
      },
      filter () {
        if (!this.form.name) {
          this.$message.error('请输入材料的名称！')
          return false
        }
        if (!this.form.brandId) {
          this.$message.error('请选择材料品牌！')
          return false
        }
        if (!this.form.materialModel) {
          this.$message.error('请输入材料型号！')
          return false
        }
        if (!this.form.styles.length) {
          this.$message.error('请选择材料所属业态！')
          return false
        }
        if (!this.form.category) {
          this.$message.error('请选择材料分类！')
          return false
        }
        if (!this.form.supplyCycle) {
          this.$message.error('请输入供货周期！')
          return false
        }
        if (!this.form.serviceTime) {
          this.$message.error('请输入预计送样时间！')
          return false
        }
        // if (!this.form.materialTextureSu.length) {
        //   this.$message.error('请你上传的材料贴图！')
        //   return false
        // }
        return true
      },
      async submitDraft () {
        
      },
      
      
      async submit (val) {
        try {
          if (this.locking) return
          this.locking = true
          const filter = this.filter()
          if (!filter) {
            this.locking = false
            return
          }
          if (val !== 'draft') {
            if (!this.form.fileGridMapping.length) {
              this.$message.error('请上传材料主图！')
              this.locking = false
              return false
            }
            if (!this.form.materialDetail.length) {
              this.$message.error('请你上传的材料详情图！')
              this.locking = false
              return false
            }
            let num = 0
            let countStatus = 0
            let storeCount = 0
            let reg = /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/
            let reg1 = /^[+]{0,1}(\d+)$/
            let specFilter = this.form.spec.items.every(item => {
              let isChildName = item.values.every(row => !!row.name)
              return item.name && item.values.length && isChildName
            })
            if (!specFilter) {
              this.$message.error('请仔细检查材料规格是否有未填写的字段！')
              this.locking = false
              return
            }
            this.form.spec.prices.body.forEach((item, index) => {
              let len = item.length
              if (reg.test(parseFloat(item[len - 5])) && reg.test(parseFloat(item[len - 4])) && reg.test(parseFloat(item[len - 3]))) num++
              if (parseInt(item[len - 1]) && reg.test(item[len - 1])) storeCount++
              if (reg1.test(item[len - 1])) countStatus++
            })
            if (num !== this.form.spec.prices.body.length) {
              this.$message.error('请输入正确的SKU价格！')
              this.locking = false
              return
            }
            if (countStatus !== this.form.spec.prices.body.length) {
              this.$message.error('请仔细检查您设置的库存是否为正整数！')
              this.locking = false
              return
            }
            if (!storeCount) {
              this.$message.error('SKU中至少有一项规格必须有库存！')
              this.locking = false
              return
            }
            if (!this.form.attr.length) {
              this.$message.error('材料属性至少有一项！')
              this.locking = false
              return
            }
            let attrFilter = this.form.attr.every(item => {
              let isChildName = item.values.every(row => !!row.name)
              return item.name && item.values.length && isChildName
            })
            if (!attrFilter) {
              this.$message.error('请仔细检查材料属性是否有未填写的字段！')
              this.locking = false
              return
            }
            if (this.form.fixParams.length) {
              let isValid = this.form.fixParams.every(item => !!item.attributeValue)
              if (!isValid) {
                this.$message.error('请仔细检查固定属性是否有未填写的字段！')
                this.locking = false
                return
              }
            }
            if (this.form.descriptions.length) {
              let isValid = this.form.descriptions.every(item => !!item.attributeValue)
              if (!isValid) {
                this.$message.error('请仔细检查其他说明是否有未填写的字段！')
                this.locking = false
                return
              }
            }
          }
          this.submitLoading = this.$loading({
            lock: true,
            text: '数据提交中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          let queryData = { ...this.form }
          queryData.items = queryData.spec.items
          queryData.table = queryData.spec.prices
          if (val === 'draft') queryData.type = 0
          else queryData.type = 1
          await this.$axios.post(saveOrUpdate, { content: { ...queryData } })
          this.submitLoading.close()
          this.$message.success(this.$route.params.id ? '修改成功！' : '添加成功！')
          this.locking = false
          this.$router.back()
        } catch (err) {
          this.submitLoading.close()
          this.locking = false
          console.log(err)
          this.$message.error(err.msg)
        }
      },
      // 获取供应商信息
      async getSupplierInfo () {
        try {
          /* eslint-disable */
          const { data: { suppliers_name, suppliers_id } } = await this.$axios.get(getSupplierInfo)
          this.supplier_name = suppliers_name
          this.suppliers_id = suppliers_id
        } catch ({ msg }) {
          this.$message.error(msg)
        }
      },
    },
    mounted () {},
    async beforeRouteEnter (to, from, next) {
      next(async vm => {
        vm.getStyle()
        await vm.getRegion()
        await vm.getCategories('stair')
        await vm.getBrands()
        await vm.getCateModelList()
        if (to.params.id) await vm.init()
        else await vm.getDefaultModel()
      })
    },
    async beforeRouteUpdate (to, from, next) {
      next()
      this.getStyle()
      await this.getRegion()
      await this.getCategories('stair')
      await this.getBrands()
      await this.getCateModelList()
      if (to.params.id) await this.init()
      else await this.getDefaultModel()
    }
  }
  </script>
  
  <style scoped lang="scss">
  .upload {
    background: #FFFFFF;
    border-radius: 4px;
  }
  .upload-body {
    padding: 0 32px 16px;
  }
  .upload-container {
    padding: 20px;
  }
  .upload-header {
    display: flex;
    align-items: center;
    .upload-header-title {
      margin-left: 10px;
      font-size: 16px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #333333;
      line-height: 22px;
    }
  }
  .upload-content {
    margin-top: 40px;
  }
  .upload-form-bd {
    margin-bottom: 20px;
    background: #fff;
    transition: all .5s;
  }
  .upload-form-bd-header {
    width: 100%;
    padding: 10px 20px;
    margin-bottom: 20px;
    background: #FAFAFA;
    display: flex;
    align-items: center;
  }
  .form-bd-title {
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    line-height: 20px;
  }
  .form-item {
    display: flex;
    align-items: center;
    margin-top: 15px;
    font-size: 12px;
    color: #333333;
    &.form-item-start {
      align-items: flex-start;
      .form-item-label {
        line-height: 60px;
        margin-right: 20px;
      }
    }
    &.spec-sku {
      .form-item-label {
        line-height: 20px;
        margin-right: 20px;
      }
    }
    &.form-item-top {
      align-items: flex-start;
    }
    & .form-item-body {
      display: flex;
      align-items: center;
      width: 1000px;
    }
    & .form-item-label {
      min-width: 110px;
      text-align: right;
      margin-right: 10px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 20px;
      &.form-item-label_import {
        &:after {
          content: '*';
          color: #FF0000;
        }
      }
      &.form-item-label_strong {
        font-weight: 600;
        font-size: 14px;
      }
    }
    & .form-item-bd {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      margin-left: 5px;
      min-width: 340px;
      & .el-checkbox-group {
        margin-right: 40px;
        & .el-checkbox {
          margin-right: 20px;
        }
      }
      & .form-item-bd_input {
        display: flex;
        min-width: 130px;
        margin-bottom: 6px;
        height: 40px;
        line-height: 40px;
        padding-left: 21px;
        align-items: center;
        & .el-input {
          width: 200px;
          margin-right: 10px;
        }
        & .form-item-bd_input-value {
          color: #0f73e6;
          cursor: pointer;
          text-decoration: underline;
        }
      }
    }
    & .form-item-bd_setting {
      display: flex;
      align-items: center;
      margin-left: 5px;
      margin-right: 10px;
      width: 150px;
      max-width: 150px;
    }
  }
  .table-td-del {
    color: #666666;
    cursor: pointer;
  }
  .model-body {
    max-height: 200px;
    overflow-y: auto;
    .model-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 5px 10px;
    }
    .model-item-title {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 20px;
    }
    .model-item-handle {
      display: flex;
      align-items: center;
      .iconfont {
        margin-left: 10px;
      }
    }
    .model-item-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      line-height: 20px;
    }
    .model-item {
      padding: 9px 20px;
      border-bottom: 1px solid #DDDDDD;
      cursor: pointer;
      &:hover {
        background: #F8F8F8;
        .model-item-setting {
          display: inline-block;
        }
        .model-item-time_handle {
          display: inline-block;
        }
      }
    }
    .model-item-default {
      font-size: 14px;
      color: #333333;
    }
    .model-item-setting {
      display: none;
      font-size: 14px;
      color: #0f73e6;
      cursor: pointer;
    }
    .model-item-time {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 10px;
      line-height: 20px;
      .model-item-time_bd {
        font-size: 14px;
        color: #999999;
      }
      .model-item-time_handle {
        display: none;
        font-size: 14px;
        color: #C2212A;
      }
    }
  }
  .spec-table {
    margin-bottom: 20px;
  }
  .spec-table-header {
    width: 100%;
    height: 60px;
    padding: 0 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #FAFAFA;
    border: 1px solid #D9D9D9;
  }
  .spec-hd-value {
    display: flex;
    align-items: center;
    .spec-hd-value-label {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 20px;
    }
    .spec-hd-value-bd {
      width: 108px;
      margin-left: 20px;
    }
  }
  .spec-hd-handle {
    display: flex;
    align-items: center;
    cursor: pointer;
    .iconfont {
      font-size: 14px;
      background: #999999;
    }
    .spec-hd-handle-btn {
      margin-left: 10px;
      font-size: 14px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #666666;
      line-height: 20px;
      cursor: pointer;
    }
  }
  .form-item-spec {
    flex: 1;
  }
  .spec-table-handle {
    margin-top: 20px;
    display: flex;
    align-items: center;
    .spec-table-handle-info {
      margin-left: 10px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #CCCCCC;
      line-height: 20px;
    }
  }
  .spec-table-body {
    padding: 24px 46px;
    background: #FFFFFF;
    border: 1px solid #D9D9D9;
    border-top: none;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    .spec-table-body-label {
      margin-right: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 20px;
      flex-shrink: 0;
      margin-bottom: 10px;
    }
    .spec-table-body-value {
      display: flex;
      align-items: center;
      margin-right: 20px;
      margin-bottom: 10px;
      .spec-table-body-input {
        position: relative;
        width: 108px;
        & .iconfont {
          display: none;
          position: absolute;
          top: 0;
          right: 0;
          font-size: 16px;
          transform: translate(50%, -50%);
          z-index: 99;
          cursor: pointer;
        }
        &:hover {
          & .iconfont {
            display: inline-block;
          }
        }
      }
      .spec-table-body-img {
        position: relative;
        width: 28px;
        height: 28px;
        margin-left: 10px;
        background: #FFFFFF;
        border: 1px solid #DDDDDD;
        background-position: center;
        background-repeat: no-repeat;
        background-size: contain;
        .iconfont {
          position: absolute;
          top: 0;
          right: 0;
          font-size: 16px;
          transform: translate(50%, -50%);
        }
      }
      .spec-table-body-upload {
        position: relative;
        margin-left: 10px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #999999;
        line-height: 20px;
        cursor: pointer;
        & .el-input {
          width: 68px;
          height: 28px;
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          opacity: 0;
        }
      }
    }
    .spec-table-body-ft {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #0F73E6;
      line-height: 20px;
      cursor: pointer;
      margin-bottom: 10px;
    }
  }
  .spec-sku-table {
    flex: 1;
    .spec-sku-info {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      line-height: 20px;
    }
  }
  .form-item-bd-info {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 20px;
  }
  .form-item-bd .el-select {
    width: 160px;
    margin-right: 10px;
  }
  .form-item .form-item-bd.form-item-width {
    flex: 1;
  }
  .form-bd-select {
    width: 150px;
    height: 28px;
    padding: 4px 10px;
    margin-left: 20px;
    background: #FFFFFF;
    border-radius: 2px;
    border: 1px solid #D9D9D9;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    color: #333333;
    cursor: pointer;
    .form-bd-select-value {
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      line-height: 20px;
      &.form-bd-select-value-placeholder {
        color: #ccc;
      }
    }
  }
  .form-bd-header-handle {
    display: flex;
    align-items: center;
    .form-bd-header-btn {
      padding: 5px 18px;
      margin-left: 20px;
      background: #ECECEC;
      border-radius: 2px;
      font-size: 13px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 18px;
      cursor: pointer;
    }
  }
  .form-item-add {
    width: 110px;
    height: 110px;
    margin-right: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    &.form-item-add_upload {
      cursor: pointer;
      border: 1px dashed #999;
    }
    &.form-item-add_img {
      position: relative;
      background-position: center;
      background-repeat: no-repeat;
      background-size: contain;
      cursor: pointer;
      & .el-checkbox-iconfont {
        position: absolute;
        right: -8px;
        top: -8px;
        font-size: 16px;
        display: none;
      }
      & .form-item-add_operation {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        width: 100%;
        height: 25px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(0,0,0,0.50);
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #FFFFFF;
        line-height: 17px;
      }
      .form-item-add_tag {
        position: absolute;
        top: 0;
        left: 0;
        width: 45px;
        height: 18px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(0,0,0,0.50);
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #FFFFFF;
        line-height: 17px;
      }
    }
    & .el-icon-plus {
      display: block;
      font-size: 36px;
      color: #999
    }
    & .form-item-add_text {
      margin-top: 10px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      line-height: 20px;
    }
  }
  .form-item-ft {
    margin-left: 10px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #0F73E6;
    line-height: 20px;
    cursor: pointer;
  }
  // .form-item-add_img:hover .form-item-add_operation {
  //   display: inline-block;
  // }
  .form-item-add_img:hover .el-checkbox-iconfont {
    display: inline-block;
  }
  .upload-footer {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 60px;
    background: #FFFFFF;
    box-shadow: 0px -1px 0px 0px #D9D9D9;
    .upload-save {
      margin-right: 20px;
    }
  }
  .table-list {
    & .table-tr {
      display: flex;
      & .table-td {
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 44px;
        min-width: 100px;
        flex: 1;
        border: 1px solid #DDD;
        border-top: none;
        border-right: none;
        &:last-child {
          border-right: 1px solid #DDD;
        }
        & .table-td-body {
          text-align: center;
          &.table-td-input {
            width: 100px;
          }
        }
      }
    }
  }
  .upload-hidden {
    opacity: 0;
  }
  .icon-move {
    cursor: move;
  }
  .form-item-info {
    margin-left: 10px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #CCCCCC;
    line-height: 20px;
  }
  .form-item-file {
    display: flex;
    align-items: center;
    .form-file-icon {
      font-size: 20px;
      color: #0F73E6;
      margin-right: 15px;
    }
    .form-file-name {
      font-size: 14px;
      color: #0F73E6;
      margin-right: 15px;
    }
    .form-file-handle {
      font-size: 14px;
      color: #666666;
      cursor: pointer;
    }
  }
  .form-item-fixed-attr {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
  }
  .fixed-attr-item {
    width: 50%;
    margin-bottom: 20px;
    .fixed-attr-item-bd {
      padding: 0 15px;
    }
    .fixed-attr-item-header {
      width: 100%;
      height: 60px;
      padding: 0 30px;
      display: flex;
      align-items: center;
      background: #FAFAFA;
      border: 1px solid #D9D9D9;
      .fixed-attr-item-header_label {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #333333;
        line-height: 20px;
      }
      .fixed-attr-item-header_value {
        margin-left: 20px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #333333;
        line-height: 20px;
      }
    }
    .fixed-attr-item-value {
      padding: 24px 46px;
      background: #FFFFFF;
      border: 1px solid #D9D9D9;
      border-top: none;
      display: flex;
      align-items: center;
      .fixed-attr-item-value_label {
        margin-right: 20px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #333333;
        line-height: 20px;
        flex-shrink: 0;
        margin-bottom: 10px;
      }
      .fixed-attr-item-value_bd {
        display: flex;
        align-items: center;
        margin-right: 20px;
        margin-bottom: 10px;
      }
    }
  }
  .form-description-item {
    margin-bottom: 20px;
  }
  </style>
  